/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.ciko.code.bean.UserBean;
import com.mywork.WorkUIKit;
import com.netease.nim.demo.NimCache;
import com.netease.nim.demo.config.preference.Preferences;
import com.netease.nim.demo.database.DatabaseManager;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.shwread.android.qysw.activity.AdvertisementActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.NewLoginActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.http.util.Logger;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.UserLoginAction;
import com.shwread.httpsdk.util.Base64;
import com.tgx.tina.android.ipc.framework.IUIPage;

import java.util.Timer;
import java.util.TimerTask;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.AdvertisementInfo;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.TaiBaoLogin;


/**
 * @Project： Lqyd_Android
 * @Title：SplashPage
 * @Description：
 * @Author：wayne
 * @Date：2014年8月12日下午11:12:00
 */
public class SplashPage
        extends
        AbstractUIPage<MainActivity> {
    // 延迟3秒
    private static final long SPLASH_DELAY_MILLIS = 3000;

    private UserDao userDao;
    private UserBean user;
    private AdvertisementInfo adinfo = new AdvertisementInfo();

    private ImageView startImg;

    private Timer mTimer;
    private static SplashPage instance;

    /**
     * @return the instance
     */
    public static SplashPage getInstance(MainActivity t) {
        if (null == instance) {
            instance = new SplashPage(t);
        }
        return instance;
    }

    /**
     * <p>
     * Title:
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param t
     */
    public SplashPage(MainActivity t) {
        super(t);
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.start, null);
        initData();
        initView();
        return curMyView;
    }

    void initData() {
        userDao = UserDao.getInstance(bActivity);
    }

    void initView() {
        startImg = (ImageView) curMyView.findViewById(R.id.start);
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        bActivity.getUIHandler().sendEmptyMessageDelayed(DefaultConsts.UPDATEUI_SPLASH_DELAY_MILLIS, SPLASH_DELAY_MILLIS);
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case DefaultConsts.UPDATEUI_SPLASH_DELAY_MILLIS:
                user = userDao.getLastLoginUser();
                if (null != user && user.getIsKeepPwd() == 1) {
                    System.out.println("最后一次登录的用户：" + user.toString());
                    mTimer = new Timer();
                    setTimerTask();
                    Intent intent = new Intent(bActivity, AdvertisementActivity.class);
                    bActivity.startActivity(intent);
                } else {
                    Intent intent = new Intent(bActivity, AdvertisementActivity.class);
                    bActivity.startActivity(intent);
                    bActivity.finish();
                }
                break;
        }

    }

    private void setTimerTask() {
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                myHandler.sendMessage(message);
            }
        }, 1000);
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int msgId = msg.what;
            switch (msgId) {
                case 1:
                    Const.clear();
                    new UserLoginAction(bActivity, user.getAccount(), Base64.decode(user.getPassword(), "utf-8"), new LoginAction()).start();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * @return void 返回类型
     * @throws
     * @Title: doNimlogin
     * @Description: 云信登录接口
     */
    @SuppressWarnings("unchecked")
    void doNimlogin(final UserBean user) {
        NIMClient.getService(AuthService.class).login(new LoginInfo(user.getImAccount(), user.getImToken())).setCallback(new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo param) {
                Logger.d("im login success");
                NimCache.setAccount(user.getImAccount());
                NIMClient.getService(AuthService.class).login(param);
                Preferences.saveUserAccount(user.getImAccount());
                Preferences.saveUserToken(user.getImToken());
                DatabaseManager.getInstance().open(bActivity);
                //登录成功更新到数据库
                UserDao.getInstance(bActivity).updateNeteaseAccount(user.getAccount(), user.getImAccount(), user.getImToken());
                //登录太保平台
                new TaiBaoLogin().LogintaibaoLogin(context, user.getAccount(), new TaiBaoLogin.LoginTaiBaoListener() {
                    @Override
                    public void run() {
                        bActivity.getUIHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                //主界面
                                if (MainTabPage.getInstance(bActivity).getView() != null) {
                                    ViewGroup group = (ViewGroup) MainTabPage.getInstance(bActivity).getView().getParent();
                                    group.removeAllViews();
                                }
                                bActivity.changePage(MainTabPage.getInstance(bActivity), KEEP_LAST_STATUS);
                                bActivity.getUIHandler().sendEmptyMessage(DefaultConsts.LOGIN_OK);
                            }
                        });
                    }
                });
            }

            @Override
            public void onFailed(int code) {
                if (code == 302 || code == 404) {
                    //Toast.makeText(LoginActivity.this, "帐号或密码错误", Toast.LENGTH_SHORT).show();
                    Logger.d("im login failed: " + "帐号或密码错误");
                }
            }

            @Override
            public void onException(Throwable exception) {
                Logger.d("im login failed: " + exception.getMessage());
            }
        });
    }

    private class LoginAction
            extends
            BaseAction {
        @Override
        public void OK(Object obj) {

            logic.bean.LoginInfo info = (logic.bean.LoginInfo) obj;
            Const.UserRole = info.getUserRole();//设置登陆者的身份类型
            Const.UserAccId = info.getAccId();//设置登陆者的accId 云信侧的Id
            Const.UserStaffId = info.getStaffId();
            user.setKey(info.getKey());
            user.setLoginTime(System.currentTimeMillis());
            user.setImAccount(info.getAccId());
            user.setImToken(info.getToken());
            user.setStaffId(info.getStaffId());
            userDao.addUser(user);
            WorkUIKit.setAccount(user.getAccount());
            WorkUIKit.setUserId(user.getStaffId());
            //登录云信
            doNimlogin(user);
        }

        @Override
        protected void onError() {
            super.onError();
            goLoginActivity();
        }
    }

    void goLoginActivity() {
        Intent intent = new Intent();
        intent.setClass(bActivity, NewLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        bActivity.startActivity(intent);
        bActivity.finish();
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        // TODO Auto-generated method stub
        return null;
    }

}
